using System;
using System.Collections;
using UnityEngine;

/****************************************************
// 功能：
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/2/21 16:33:51
*****************************************************/

public class AudioManager : SingletonPatternMonoBase<AudioManager>, IManager
{
    private AudioSource bgmAudio;
    private AudioSource uiAudio;
    
    public void InitManager()
    {
        //Debug.Log("AudioManager Init");
        bgmAudio = transform.Find("BgmAudio").GetComponent<AudioSource>();
        uiAudio = transform.Find("UIAudio").GetComponent<AudioSource>();
    }

    public bool isOn
    {
        get =>
            PlayerPrefs.GetInt("IsAudioOn", 1) == 1;
        set
        {
            PlayerPrefs.SetInt("IsAudioOn", value ? 1 : 0);
            PlayerPrefs.Save();
        }
    }

    public void PlayBGMusic(string name, bool isLoop = true)
    {
        if (isOn)
        {
            var clip = ResourceManager.Instance.LoadAudio("Audio/" + name, true);
            if (bgmAudio.clip != null && bgmAudio.clip.name == clip.name) return;
            bgmAudio.clip = clip;
            bgmAudio.loop = isLoop;
            bgmAudio.Play();
        }
        else
        {
            bgmAudio.Stop();
        }
    }
    
    public void PlayUIAudio(string name)
    {
        if (isOn)
        {
            var clip = ResourceManager.Instance.LoadAudio("Audio/" + name, true);
            uiAudio.clip = clip;
            uiAudio.Play(); 
        }
        else
        {
            uiAudio.Stop();
        }
        
    }
    
    public void StopBgMusic()
    {
        if (bgmAudio != null) { bgmAudio.Stop(); }
    }

    public void PlayEntityAudio(string name, AudioSource audioSource, bool loop = false, int delay = 0)
    {
        if (!isOn) { return; }

        void PlayAudio()
        {
            var clip = ResourceManager.Instance.LoadAudio("Audio/" + name, true);
            audioSource.clip = clip;
            audioSource.loop = loop;
            audioSource.Play(); 
        }
        
        if (delay == 0)
        {
            PlayAudio();
        }
        else
        {
            StartCoroutine(DelayPlayAudio(delay * 1.0f / 1000, PlayAudio));
        }
    }

    private static IEnumerator DelayPlayAudio(float sec, Action action)
    {
        yield return new WaitForSeconds(sec);
        action?.Invoke();
    }
}
